package ch.ti.bfh.app.loodel.internal.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

import javax.persistence.EntityManager;
import java.io.Serializable;

import static org.springframework.data.querydsl.QueryDslUtils.QUERY_DSL_PRESENT;

public class GlobalRepositoryFactoryBean<R extends JpaRepository<T, I>, T, I extends Serializable> extends JpaRepositoryFactoryBean<R, T, I> {

    protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
        return new GlobalRepositoryFactory(entityManager);
    }

    private static class GlobalRepositoryFactory<T, I extends Serializable> extends JpaRepositoryFactory {
        private EntityManager entityManager;

        public GlobalRepositoryFactory(EntityManager entityManager) {
            super(entityManager);
            this.entityManager = entityManager;
        }

        protected Object getTargetRepository(RepositoryMetadata metadata) {

            Class<?> repositoryInterface = metadata.getRepositoryInterface();
            JpaEntityInformation<?, Serializable> entityInformation = getEntityInformation(metadata.getDomainType());

            SimpleJpaRepository<?, ?> repo = new DefaultGlobalRepository(entityInformation, entityManager);
            //repo.setLockMetadataProvider(lockModePostProcessor.getLockMetadataProvider());
            return repo;
        }

        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
            return DefaultGlobalRepository.class;
        }

        /**
         * Returns whether the given repository interface requires a QueryDsl specific implementation to be chosen.
         *
         * @param repositoryInterface
         * @return
         */
        private boolean isQueryDslExecutor(Class<?> repositoryInterface) {

            return QUERY_DSL_PRESENT && QueryDslPredicateExecutor.class.isAssignableFrom(repositoryInterface);
        }
    }


}